// const BaseRest = require('./rest.js');
const BaseRest = require('./rest.js');

module.exports = class extends BaseRest {
  constructor(ctx) {
    super(ctx);
    this.modelInstance = this.model('user');
  }

  // 这个版本有安全问题，应该需要授权才能访问别人的信息
  // 所有的请求否必须登陆
  async __before(action) {
    try {
      this.userInfo = await this.ctx.session('userInfo');
    } catch (err) {
      this.userInfo = {};
    }

    // GET请求都必须登陆
    if (think.isEmpty(this.userInfo)) {
      this.ctx.status = 401;
      return this.ctx.fail(-1, '请登录后操作');
    }
  }

  // 查询用户信息
  async getAction() {
    // APP客户端只允许用户看自己的信息
    const userInfo = this.userInfo;
    // think.logger.info(userInfo);
    if (think.isEmpty(userInfo)) {
      this.ctx.status = 401;
      return this.ctx.fail(-1, '请登录后操作');
    }

    let data;

    // 根据ID查询
    if (this.getId()) {
      think.logger.info(userInfo);

      if (this.getId() != userInfo.id) {
        this.ctx.status = 401;
        return this.ctx.fail(-2, '只允许查看自己的信息');
      }

      // data = await this.modelInstance.where({ id: this.getId()}).fieldReverse('password,encrypt,last_login_ip,last_login_time').find();
      data = await this.modelInstance.where({ id: this.getId()}).field('id,username,email,mobile').find();
      data.avator = 'https://secure.gravatar.com/avatar/' + think.md5(data.email);
      return this.success(data);
    }

    // 根据用户名查询信息
    const username = this.get('username');
    if (!think.isEmpty(username)) {
      if (username != userInfo.username) {
        this.ctx.status = 401;
        return this.ctx.fail(-2, '只允许查看自己的信息');
      }

      data = await this.modelInstance.where({ username: username }).fieldReverse('password,encrypt').find();
      data.avator = 'https://secure.gravatar.com/avatar/' + think.md5(data.email);
      return this.success(data);
    }

    // 分页查找，需要验证更多的权限，是否能够列用户信息

    // data = await this.modelInstance.fieldReverse('password,encrypt').select();
    // let map = {};
    // // 页码
    // const page = this.get('page') || 1;
    // // 每页显示数量
    // const pageSize = this.get('pageSize') || 5;
    // data = await this.modelInstance.where(map).page(page, pageSize).order('create_time desc').fieldReverse('password,encrypt').countSelect();

    // data.data.forEach(element => {
    //   element.avator = 'https://secure.gravatar.com/avatar/' + think.md5(element.email);
    // });

    // return this.success(data);
  }

  async postAction() {
    const data = this.post();
    // 用户注册
    const user = await this.modelInstance.where({ username: data['username'] }).find();
    if (!think.isEmpty(user)) {
      return this.fail(-1, '用户名已经存在');
    }

    data['encrypt'] = think.service('utils').getRamdomString(10, {});
    data['password'] = think.service('utils').getEncryptPassword(data['password'], data['encrypt']);
    data['create_ip'] = this.ctx.ip;
    data['create_time'] = Math.round((new Date()).getTime() / 1000);
    const ret = await this.modelInstance.addUser(data);

    think.logger.debug(ret);
    return this.success(ret);
  }

  // 更新用户信息
  async putAction() {
    // 删除缓存
    think.cache('user', null);

    const userInfo = this.userInfo;
    const data = this.post();
    if (think.isEmpty(data)) {
      return this.fail(1000, '数据不能为空');
    }
    const rows = await this.modelInstance.where({ id: userInfo.id }).update(data);
    if (rows) {
      return this.success({ affectedRows: rows }, '更新成功');
    } else {
      return this.fail(1000, '更新失败');
    }
  }

  /**
   * 删除内容
   * @return {[type]} [description]
   */
  async deleteAction() {
    if (!this.id) {
      return this.fail(1001, '用户不存在');
    }
    // 软删除标志
    const rows = await this.modelInstance.where({ id: this.id }).update({ deleted_flag: 1 });
    if (rows) {
      await this.hook('userDelete', { id: this.id });
      return this.success({ affectedRows: rows }, '删除成功');
    } else {
      return this.fail(1000, '删除失败');
    }
  }
};
